package com.redrose.videodemo.runnabletask;

import android.content.Context;
import android.media.AudioRecord;

import com.redrose.videodemo.utils.AudioRecordUtil;
import com.redrose.videodemo.utils.LogUtils;
import com.redrose.videodemo.utils.PathUtil;
import com.redrose.videodemo.utils.ToastUtil;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Desc:
 *
 * @Author: RedRose
 * Date: 2019/4/15 0015
 * Email: yinsxi@163.com
 */
public class AudioRecordRunnable implements Runnable {
    private Context mContext;

    public AudioRecordRunnable(Context mContext) {
        this.mContext = mContext;
    }

    @Override
    public void run() {
        AudioRecordUtil.getInstance().setRecordStatues(true);
        int recordBufSize = AudioRecordUtil.getInstance().getmRecordBufSize();
        AudioRecord audioRecord = AudioRecordUtil.getInstance().getAudioRecord(recordBufSize);
        final byte[] buffer = new byte[recordBufSize];
        File file = new File(PathUtil.getAppAudioPath());
        if (!file.exists()) {
            file.mkdir();
        }
        File pcmFile = new File(PathUtil.getAppAudioPath(), "audio.pcm");
        if (pcmFile.exists()) {
            pcmFile.delete();
        }
        DataOutputStream outputStream = null;
        try {
            pcmFile.createNewFile();
            outputStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(pcmFile)));
            //开始录音
            audioRecord.startRecording();
            int r = 0;
            while (AudioRecordUtil.getInstance().isRecording()
                    && audioRecord.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING) {
                int readResult = audioRecord.read(buffer, 0, recordBufSize);
                // 如果读取音频数据没有出现错误，就将数据写入到文件
                if(AudioRecord.ERROR_INVALID_OPERATION != readResult){
                    outputStream.write(buffer);
                }

            }
            AudioRecordUtil.getInstance().releaseAudioRecord();
            outputStream.close();
            LogUtils.d("AudioRecordRunnable","停止录音");
            ToastUtil.show(mContext.getApplicationContext(),"停止录音");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
